<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" class="flex" style="justify-content: flex-end">
        <el-button v-if="statusCheck" type="primary" @click="changeEdit"
          >编辑</el-button
        >
        <el-button v-else type="primary" @click="submitForm">提交</el-button>
      </el-col>
    </el-row>

    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="新增知识产权" name="first">
        <div
          class="flex align-center"
          style="width: 100%; color: #1890ff; font-size: 1rem"
        >
          <!-- <i
            class="el-icon-tickets"
            style="margin-right: 0.25rem; font-size: 1.2rem"
          ></i>
          <span style="margin-top: 0.25rem">新增知识产权</span> -->
        </div>
        <el-divider></el-divider>
        <el-form
          ref="informationForm"
          :model="formData"
          :rules="rules"
          size="medium"
          label-width="8rem"
        >
          <!-- <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="企业名称" prop="companyName">
                <el-input
                  v-model="formData.companyName"
                  placeholder="请输入企业名称"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row :gutter="15">
            <el-col :span="10">
              <el-form-item label="统一信用代码" prop="creditCode">
                <el-input
                  v-model="formData.creditCode"
                  placeholder="请输入统一信用代码"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="注册地址" prop="registeredAddress">
                <el-input
                  v-model="formData.registeredAddress"
                  placeholder="请输入注册地址"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row :gutter="15">
            <el-col :span="10">
              <el-form-item label="类别" prop="typeId">
                <el-select
                  v-model="formData.typeId"
                  placeholder="请选择类别"
                  clearable
                  :style="{ width: '100%' }"
                  :disabled="statusCheck"
                >
                  <el-option
                    v-for="(item, index) in typeIdOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="获取方式" prop="method">
                <el-select
                  v-model="formData.method"
                  placeholder="请选择获取方式"
                  clearable
                  :style="{ width: '100%' }"
                  :disabled="statusCheck"
                >
                  <el-option
                    v-for="(item, index) in methodOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="10">
              <el-form-item label="证书号" prop="certificateCode">
                <el-input
                  v-model="formData.certificateCode"
                  placeholder="请输入证书号"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="statusCheck"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="专利号/著作权号" prop="patentNumber">
                <el-input
                  v-model="formData.patentNumber"
                  placeholder="请输入专利号/著作权号"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="statusCheck"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="10">
              <el-form-item label="专利名称" prop="patentName">
                <el-input
                  v-model="formData.patentName"
                  placeholder="请输入专利名称"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="statusCheck"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="8">
              <el-form-item label="授权日期" prop="authorizationTimeStr">
                <el-date-picker
                  v-model="formData.authorizationTimeStr"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{ width: '100%' }"
                  placeholder="请选择授权日期"
                  clearable
                  :readonly="statusCheck"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="8">
              <el-form-item label="有效日期" prop="effectiveTimeStr">
                <el-date-picker
                  v-model="formData.effectiveTimeStr"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{ width: '100%' }"
                  placeholder="请选择有效日期"
                  clearable
                  :readonly="statusCheck"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="缴费日期" prop="paymentTimeStr">
                <el-date-picker
                  v-model="formData.paymentTimeStr"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{ width: '100%' }"
                  placeholder="请选择缴费日期"
                  clearable
                  :readonly="statusCheck"
                ></el-date-picker>
              </el-form-item>
            </el-col> -->
          </el-row>

          <el-row :gutter="16">
            <el-col :span="24">
              <el-form-item label="相关附件" prop="fileList">
                <el-upload
                  ref="fileList"
                  :file-list="relatedAccessoryfileList"
                  :action="relatedAccessoryAction"
                  :headers="relatedAccessoryHeaders"
                  multiple
                  :before-upload="handleBeforeUpload"
                  :before-remove="handleBeforeRemoveUpload"
                  :on-preview="fileListClick"
                  :on-success="handleSuccessUpload"
                  :disabled="statusCheck"
                >
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >上传文件</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    只能上传不超过 10MB 的文件
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start" align="top" :gutter="16">
            <el-col :span="12">
              <el-form-item label="创建者" prop="createUserName">
                <el-input
                  v-model="formData.createUserName"
                  placeholder="请输入创建者"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="true"
                ></el-input>
              </el-form-item>
              <el-form-item v-show="false" label="创建id" prop="creatorId">
                <el-input
                  v-model="formData.creatorId"
                  placeholder="请输入创建者ID"
                  clearable
                  :style="{ width: '100%' }"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="修改记录" name="fourth" v-if="false">
        <el-table
          ref="tableRef"
          :data="tableData5"
          size="mini"
          row-key="id"
          border
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="序号" prop="id" align="center" />
          <el-table-column
            label="方法名称"
            prop="methodName"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="修改数据"
            prop="updateData"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="创建者"
            prop="createBy"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column label="修改时间" prop="createTime" align="center">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { downloadFile } from "@/api";
import { getToken } from "@/utils/auth";
// import { treeselect } from '@/api/system/dept';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getUserList } from "@/api/enterprise/information";
import {
  addCompanyCopyright,
  addSystemMessage,
  getCompanyCopyrightTypeList,
  getCompanyCopyrightById,
  getCompanyInfoNotice,
  getCompanyInfoLog,
  updateCompanyCopyright,
  updateCompanyInfoNotice
} from "@/api/enterprise/intellectual";

export default {
  components: { Treeselect },
  props: [],
  data() {
    return {
      // 当前是否为查看状态
      statusCheck: false,
      // 当前知识产权分表的id
      id: undefined,
      // tabs选项卡
      activeName: "first",
      // 表单
      formData: {
        companyId: undefined,
        companyName: undefined,
        creditCode: undefined,
        registeredAddress: undefined,
        typeId: undefined,
        method: undefined,
        certificateCode: undefined,
        patentNumber: undefined,
        patentName: undefined,
        authorizationTimeStr: null,
        effectiveTimeStr: null,
        paymentTimeStr: null,
        fileList: [],
        creatorId: this.$store.state.user.userId,
        createUserName: this.$store.state.user.name
      },
      rules: {
        companyName: [
          {
            required: true,
            message: "请输入企业名称",
            trigger: "blur"
          }
        ],
        creditCode: [
          {
            required: true,
            message: "请输入统一信用代码",
            trigger: "blur"
          }
        ],
        registeredAddress: [
          {
            required: true,
            message: "请输入注册地址",
            trigger: "blur"
          }
        ],
        typeId: [
          {
            required: true,
            message: "请选择类别",
            trigger: "change"
          }
        ],
        method: [
          {
            required: true,
            message: "请选择获取方式",
            trigger: "change"
          }
        ],
        certificateCode: [
          {
            required: true,
            message: "请输入证书号",
            trigger: "blur"
          }
        ],
        patentNumber: [
          {
            required: true,
            message: "请输入专利号/著作权号",
            trigger: "blur"
          }
        ],
        patentName: [
          {
            required: true,
            message: "请输入专利名称",
            trigger: "blur"
          }
        ],
        authorizationTimeStr: [
          {
            required: true,
            message: "请选择授权日期",
            trigger: "change"
          }
        ],
        effectiveTimeStr: [
          {
            required: true,
            message: "请选择有效日期",
            trigger: "change"
          }
        ],
        paymentTimeStr: [
          {
            required: true,
            message: "请选择缴费日期",
            trigger: "change"
          }
        ]
      },
      // select内容填充
      /* 类别 */
      typeIdOptions: [
        {
          name: "请选择",
          id: "",
          disabled: true
        }
      ],
      methodOptions: [
        {
          label: "请选择",
          value: "",
          disabled: true
        },
        {
          label: "自主研发",
          value: 0
        },
        {
          label: "并购",
          value: 1
        },
        {
          label: "其他",
          value: 2
        }
      ],

      // 上传相关参数
      relatedAccessoryAction: process.env.VUE_APP_BASE_API + "/system/upload",
      relatedAccessoryHeaders: {
        Authorization: "Bearer " + getToken()
      },
      relatedAccessoryData: {},
      relatedAccessoryfileList: [],

      /** 动态表格表单 */
      tableData4: [
        {
          id: 1,
          remindTimeStr: "",
          content: "",
          remindUserId: null,
          status: 0
        }
      ],
      tableData5: [
        // {
        //   createBy: undefined,
        //   createTime: undefined,
        //   methodName: undefined,
        //   updateData: undefined,
        // },
      ],

      /** 信息提醒->提醒人选择 */
      // 部门树选项
      deptOptions: []
    };
  },
  computed: {
    ...mapState({
      userId: state => state.user.userId,
      name: state => state.user.name
    })
  },
  watch: {},
  created() {
    this.id = this.$route.query.id;
    this.statusCheck = this.$route.query.isCheck ? true : false;

    // 为企业相关的数据赋值
    let enterpriseInfo = JSON.parse(sessionStorage.getItem("enterpriseInfo"));
    this.formData.companyId = enterpriseInfo.id;
    this.formData.companyName = enterpriseInfo.companyName;
    this.formData.creditCode = enterpriseInfo.creditCode;
    this.formData.registeredAddress = enterpriseInfo.registeredAddress;

    // 获取知识产权类别列表
    getCompanyCopyrightTypeList().then(res => {
      this.typeIdOptions = [this.typeIdOptions[0], ...res.data];
    });

    // 获取部门树
    this.getTreeselect();

    if (this.id) {
      // 获取当前企业信息
      getCompanyCopyrightById(this.id).then(res => {
        if (this.id) {
          Object.assign(this.formData, res.data);
          if (this.formData.fileList.length !== 0) {
            let fileList = this.formData.fileList;
            let newFileList = [];
            fileList.forEach((value, key) => {
              newFileList[key] = {
                name: value.fileName,
                url: value.pathName
              };
            });
            this.relatedAccessoryfileList = newFileList;
          }
        }
      });

      // getCompanyInfoNotice(this.id).then(res => {
      //   this.tableData4 = res.data;
      // });
      // getCompanyInfoLog(this.id).then(res => {
      // });
    }
  },
  mounted() {},
  methods: {
    // tabs切换
    handleClick(tab, event) {},

    // 切换编辑
    changeEdit() {
      this.statusCheck = false;
    },

    /** 普通表单 */
    // 上传之前的操作
    handleBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 10;
      if (!isRightSize) {
        this.$message.error("文件大小超过 10MB");
      }
      this.relatedAccessoryData.name = file.name;
      return isRightSize;
    },
    // 上传成功后的操作
    handleSuccessUpload(response, file, fileList) {
      this.relatedAccessoryfileList = fileList;
      // this.formData.fileList.push(res.data);
    },
    // 删除文件列表之前的操作
    handleBeforeRemoveUpload(file, fileList) {
      this.relatedAccessoryfileList = fileList;
      // return false;
    },
    /** 点击文件列表内文件的操作 */
    // 下载文件
    download(data, fileName) {
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
    },

    // 点击下载
    fileListClick(file) {
      this.$confirm("请选择对此文件的操作", "操作", {
        distinguishCancelAndClose: true,
        confirmButtonText: "阅读",
        cancelButtonText: "下载",
        type: "info",
        center: true
      })
        .then(() => {
          let fileUrl = file.url; // 文件路径
          let fileName = file.name; // 文件名
          fileUrl = "http://qypy.thinkervc.cn/file/" + fileUrl; // 完整文件路径
          let suffix = fileUrl
            .substring(fileUrl.lastIndexOf(".") + 1)
            .toLowerCase(); // 后缀名

          if (
            suffix === "doc" ||
            suffix === "docx" ||
            suffix === "xls" ||
            suffix === "xlsx" ||
            suffix === "ppt" ||
            suffix === "pptx"
          ) {
            let url = encodeURIComponent(fileUrl);
            let officeUrl =
              "http://view.officeapps.live.com/op/view.aspx?src=" + url;
            window.open(officeUrl, "_target");
          } else {
            let previewUrl = fileUrl + "&fullfilename=" + fileName; // 预览路径名
            previewUrl = this.base64.encode(fileUrl); // 转码
            window.open(
              "http://47.96.8.181:8012/onlinePreview?url=" +
                encodeURIComponent(previewUrl)
            );
          }
        })
        .catch(action => {
          if (action === "cancel") {
            // window.open(file.url, '_target');
            downloadFile({ fileName: file.name, pathName: file.url }).then(
              res => {
                this.download(res, file.name);
              }
            );
          }
        });
    },

    // 提交成功，返回上页
    back(response) {
      // 关闭当前标签页并返回上一页
      this.$message({
        message: response.msg,
        type: "success"
      });
      this.$store.dispatch("tagsView/delView", this.$route);
      // this.$router
      //   .push({
      //     path: '/manageInformation/information',
      //     query: { jumpTime: new Date().getTime() }
      //   })
      //   .catch(err => {
      //   });
      this.$router.go(-1);
    },

    // 提交
    submitForm() {
      let tempList = this.relatedAccessoryfileList.map(item => {
        if (!item.url) {
          item = item.response.data;
        }
        let tempObj = { fileName: "", pathName: "" };
        tempObj = {
          fileName: item.name || item.fileName,
          pathName: item.url || item.pathName
        };
        return tempObj;
      });
      this.formData.fileList = tempList;
      this.$refs["informationForm"].validate(valid => {
        if (!valid) {
          this.$message({
            type: "error",
            message: "基本信息有必填项未填，请输入后重试!"
          });
          this.activeName = "first";
          return;
        }
        // TODO 提交表单
        this.formData.fileArr = this.formData.fileList;
        // 过滤
        let {
          fileList,
          companyName,
          creditCode,
          registeredAddress,
          ...obj
        } = this.formData;

        if (this.tableData4) {
          this.tableData4.forEach((v, k) => {
            if (Array.isArray(this.tableData4[k].remindUserId)) {
              this.tableData4[k].remindUserId = v.remindUserId.join();
            }
          });
        }

        this.$confirm("保存按钮只能保存当页信息, 是否继续?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            if (this.activeName == "first") {
              if (this.id) {
                updateCompanyCopyright(JSON.stringify(this.formData)).then(
                  response => {
                    // updateCompanyInfoNotice(JSON.stringify(this.tableData4)).then(response => {
                    // });
                    // 关闭当前标签页并返回上一页
                    this.back(response);
                  }
                );
              } else {
                addCompanyCopyright(JSON.stringify(this.formData)).then(
                  response => {
                    // addSystemMessage(JSON.stringify(this.tableData4)).then(response => {
                    // });
                    // 关闭当前标签页并返回上一页
                    this.back(response);
                  }
                );
              }
            } else {
              addSystemMessage(JSON.stringify(this.tableData4)).then(
                response => {
                  console.log("addSystemMessage", response);
                }
              );
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      });
    },
    resetForm() {
      this.$refs["informationForm"].resetFields();
    },

    /** 动态表格表单 */
    addInput(tableName) {
      if (tableName === "tableData4") {
        if (!this.tableData4) this.tableData4 = [];
        let tableLength = this.tableData4.length;
        this.tableData4.push({
          id: tableLength + 1,
          remindTimeStr: "",
          content: "",
          remindUserId: null,
          status: 0
        });
      }
    },
    deleteInput(index, tableName) {
      if (tableName === "tableData4") {
        this.tableData4.splice(index, 1);
        let tableLength = this.tableData4.length;
        for (let i = index; i < tableLength; i++) {
          this.tableData4[i].id = i + 1;
        }
      }
    },

    /** 信息提醒->提醒人选择 */
    /** 查询部门下拉树结构 */
    getTreeselect() {
      getUserList().then(response => {
        this.deptOptions = response.data;
      });
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.userId,
        label: node.userName
      };
    }
    /** END */
  }
};
</script>

<style lang="scss" scoped>
.el-upload__tip {
  line-height: 1.2;
}

.el-divider--horizontal {
  margin: 0.75rem 0 !important;
}

.el-row {
  padding: 0.35rem;
}

/** 解决tabs切换后表格底部多出一条线 */
::v-deep .el-table:not(.el-table--scrollable-x) .el-table__fixed-right {
  height: 100% !important;
}
::v-deep .el-table__fixed {
  height: 100% !important;
}
::v-deep .el-table::before {
  z-index: inherit;
}

/** 解决在tabs/table内无法显示树的问题 */
::v-deep .el-table,
::v-deep .el-table .cell,
::v-deep .el-tabs__content,
::v-deep .el-table__body-wrapper {
  overflow: visible;
}

/** 修改表单内无法修改时的样式 */
::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: #fff;
  border-color: #dfe4ed;
  color: #333;
  /* border: 0; */
}

.dynamic-form {
  .add-input {
    padding: 0.95rem 0;
    border: 1px solid #dfdfdf;
    border-top: 0;
    cursor: pointer;

    &:hover {
      color: #409eff;
      background-color: #f5f7fa;
    }
  }
}
</style>
